package com.jxb.moniDubbo;

import com.google.protobuf.InvalidProtocolBufferException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class TestProto {

    public static void main(String[] args) {
        Demo.Person.Builder builder = Demo.Person.newBuilder();
        builder.setName("hahaha");
        builder.setId(1);
        builder.setEmail("29");
        Demo.Person.PhoneNumber.Builder builder1 = Demo.Person.PhoneNumber.newBuilder();
        builder1.setType(Demo.Person.PhoneType.MOBILE);
        builder1.setNumber("123");

        //通过消息构造器创建消息对象
        Demo.Person person = builder.build();
        //方式1：直接序列化消息
        byte[] bytes = person.toByteArray();
        System.out.println(Arrays.toString(bytes));

        //反序列化
        try {
            Demo.Person person1 = Demo.Person.parseFrom(bytes);
            System.out.println(person1.getName());
            System.out.println(person1.getEmail());
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }

        //方式2：通过输入输出流序列化和反序列化消息
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            person.writeTo(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //转成二进制流
        byte[] bytes1 = stream.toByteArray();

        //反序列化
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes1);
        try {
            Demo.Person person1 = Demo.Person.parseFrom(inputStream);
            System.out.println(person1.getId());
            System.out.println(person1.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
